import { getUserList, editUser, delUser, resetUser } from '@/api/user'

const getDefaultState = () => {
  return {
    loading: false,
    tableData: [],
    current: 1,
    size: 18,
    total: 0,
    conditins: {}
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: state => {
    Object.assign(state, getDefaultState())
  }
}

const actions = {
  // 查询
  async loadData({ state }, payload = {}) {
    const { current: newCurrent, size: newSize, ...conditins } = payload
    const newConditions = { ...state.conditins, ...conditins }
    state.loading = true
    const res = await getUserList({
      current: newCurrent || state.current,
      size: newSize || state.size,
      ...newConditions
    })
    state.loading = false
    const { retData } = res || {}
    const { records, current, size, total } = retData || {}

    Object.assign(state, {
      tableData: records || [],
      current,
      size,
      total,
      conditins: newConditions
    })
  },

  // 编辑用户
  async onEditUser({ dispatch, commit }, payload = {}) {
    const { success } = await editUser(payload)
    if (success) {
      dispatch('hideModal', {}, { root: true })
      dispatch('loadData')
    }
  },

  // 重置
  async onResetUser({ dispatch }, payload = {}) {
    const { code, userName, realName, modalKey } = payload
    const { success, retData } = await resetUser(code)

    if (success) {
      const nameStr = `${userName}(${realName})`

      dispatch(
        'showModal',
        {
          modalKey,
          modalData: {
            nameStr,
            newPwd: retData || 'xm123456'
          }
        },
        { root: true }
      )
    }
  },

  // 删除
  async onDelUser({ dispatch }, payload = {}) {
    const { code } = payload
    const { success } = await delUser(code)
    if (success) {
      dispatch('loadData')
    }
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
